﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;

namespace Magnetism.Crm4.Addons
{
    public class IncrementalNumbering
    {
        public const string SchemaName = "mag_incrementalnumbering";

        public class Fields
        {
            public const string Id = "mag_incrementalnumberingid";
            public const string EntityName = "mag_entity_schema_name";
            public const string PropertyName = "mag_property_schema_name";
            public const string CurrentPosition = "mag_current_position";
        }

        public Guid Id { get; set; }
        public string EntityName { get; set; }
        public string PropertyName { get; set; }
        public int CurrentPosition { get; set; }

        public IncrementalNumbering() { }

        public IncrementalNumbering(DynamicEntity entity)
        {
            this.Id = (entity.Properties[Fields.Id] as Key).Value;
            this.EntityName = entity.Properties[Fields.EntityName].ToString();
            this.PropertyName = entity.Properties[Fields.PropertyName].ToString();
            this.CurrentPosition = (entity.Properties[Fields.CurrentPosition] as CrmNumber).Value;
        }

        public void Increment(ICrmService service, int next)
        {
            this.CurrentPosition = next; // set before calling ToDynamic

            TargetUpdateDynamic target = new TargetUpdateDynamic();
            target.Entity = this.ToDynamic();

            UpdateRequest request = new UpdateRequest();
            request.Target = target;

            service.Execute(request);
        }

        // see if there are any increment settings for this entity
        public static IncrementalNumbering GetSettings(ICrmService service, string entityName)
        {
            IncrementalNumbering setting = null;

            QueryExpression query = new QueryExpression();

            query.EntityName = IncrementalNumbering.SchemaName;
            query.ColumnSet = new AllColumns();

            query.Criteria = new FilterExpression();
            query.Criteria.FilterOperator = LogicalOperator.And;

            ConditionExpression condition1 = new ConditionExpression();
            condition1.AttributeName = IncrementalNumbering.Fields.EntityName;
            condition1.Operator = ConditionOperator.Equal;
            condition1.Values = new object[] { entityName };

            query.Criteria.AddCondition(condition1);

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            request.ReturnDynamicEntities = true;

            RetrieveMultipleResponse response = service.Execute(request) as RetrieveMultipleResponse;
            BusinessEntityCollection results = response.BusinessEntityCollection;
            if (results.BusinessEntities.Count > 0) // no error checkig to see if there are 2 incrementors set for the same entity
            {
                setting = new IncrementalNumbering(results.BusinessEntities[0] as DynamicEntity);
            }

            return setting;
        }

        // should include rest of the fields, but leave it for now
        public DynamicEntity ToDynamic()
        {
            DynamicEntity entity = new DynamicEntity(IncrementalNumbering.SchemaName);
            PropertyCollection properties = new PropertyCollection();

            properties.Add(new KeyProperty(Fields.Id, new Key(this.Id)));
            properties.Add(new CrmNumberProperty(Fields.CurrentPosition, new CrmNumber(this.CurrentPosition)));

            entity.Properties = properties;

            return entity;
        }
    }
}
